#!/usr/bin/python
# -*- coding: utf-8 -*-
# Description: post view
# Create: Jun 8, 2008
# Author: MK2[fengmk2@gmail.com]

import datetime
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic import list_detail
from django.http import HttpResponse
from django.template.context import RequestContext
from django.template.loader import render_to_string
from django.utils import simplejson
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import ObjectDoesNotExist
#from net4.web.posts.models import Post, Comment
#from net4.web.posts.forms import CommentForm


def post_detail(request, year, month, post_id):
    # Look up the post (and raise a 404 if she's not found)
    post = get_object_or_404(Post, pk=post_id)
    if post.last_visitor_IP != request.META[u'REMOTE_ADDR']:
        post.hits += 1
        post.last_visitor_IP = request.META[u'REMOTE_ADDR']
        post.save()
    
    init_data = {u'title': u're: %s' % post.title}
    if request.user.is_authenticated():
        try:
            website = request.user.get_profile().website
        except ObjectDoesNotExist:
            website = ''
        init_data.update({u'username': request.user.username,
                    u'useremail': request.user.email,
                    u'usersite': website})
    comment_form = CommentForm(initial=init_data)
    return render_to_response(u'posts/post_detail.html', 
                              {u'post': post,
                               u'comment_list': post.comment_set.all(),
                               u'comment_form': comment_form,
                               u'title': _(post.title)},
                              context_instance=RequestContext(request))

def post_list(request, page):
    return list_detail.object_list(request, 
                                   queryset=Post.objects.all(), 
                                   paginate_by=5, 
                                   page=page, 
                                   template_object_name=u'post',
                                   extra_context={u'title': u'最新发表'})

def post_list_month(request, year, month):
    print int(month)
    return list_detail.object_list(request, 
               queryset=Post.objects.filter(
                    create_date__year=int(year),
                    create_date__month=int(month)
                                            ),
               template_object_name=u'post',
               extra_context={u'title': u'%s-%s的文章' % (year, month,)})
    
def post_list_ajax(request, page):
    return list_detail.object_list(request, 
                                   queryset=Post.objects.all(), 
                                   paginate_by=5, 
                                   page=page, 
                                   template_name=u'posts/post_list_template.html', 
                                   template_object_name=u'post')

def __get_comment_list(request, post):
    comment_list_html = render_to_string(u'posts/comment_list_template.html', 
                                    {u'comment_list': post.comment_set.all(),
                                     u'post': post},
                                     context_instance=RequestContext(request))
    return comment_list_html

def comment_add(request, post_id):
    """添加评论，返回JSON 
    {'success': T/F,
     'message': some string,
     'comment_list': comment_list_html,
     'errors': {item_auto_id: errors, ...}
    }
    """
    post = get_object_or_404(Post, pk=post_id)
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
        comment = comment_form.save(commit=False)
        comment.userIP = request.META[u'REMOTE_ADDR']
        post.comment_set.add(comment)
        post.comment_count = post.comment_set.count()
        post.save()
        comment_list_html = __get_comment_list(request, post)
        result = {u'success': True,
                  u'message': u'评论已保存',
                  u'comment_list': comment_list_html}
        data = simplejson.dumps(result, ensure_ascii=False) #将python dict转化成javascript的json对象
        return HttpResponse(data)
    else:
        errors = {}
        for item in comment_form:
            if item.errors:
                errors[item.auto_id] = unicode(item.errors)
        result = {u'success': False, u'errors': errors}
        data = simplejson.dumps(result, ensure_ascii=False)
        return HttpResponse(data)
    
@permission_required(u'posts.delete_comment')
def comment_delete(request, post_id, comment_id):
    """删除评论，返回JSON 
    {'success': T/F,
     'message': some string,
     'comment_list': comment_list_html
    }
    """
    post = get_object_or_404(Post, pk=post_id)
    is_success = True
    try:
        comment = post.comment_set.get(id=comment_id)
    except Comment.DoesNotExist:
        comment = None
        msg = u'该评论不存在.'
        is_success = False
    if comment is not None:
        msg = u'该评论已被成功删除.'
        comment.delete()
        post.comment_count = post.comment_set.count()
        post.save()
    comment_list_html = __get_comment_list(request, post)
    result = {u'success': is_success, u'message': msg, u'comment_list': comment_list_html}
    data = simplejson.dumps(result, ensure_ascii=False) #将python dict转化成javascript的json对象
    return HttpResponse(data)